<template>
  <a-card class="table-page" :bordered="false">
    <div class="box-full overflow-hidden border-box">
      <div class="flex-center mb-20 h-60">
        <span class="mr-20" v-if="itemMoment"> 素材号：{{ itemMoment.name }} </span>
        <a-input-search
          :style="{ width: '400px' }"
          placeholder="文案内容/关键字/商品ID"
          v-model="leftParams.keyword"
          search-button
          @search="onSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
          <template #button-default> 搜索 </template>
        </a-input-search>
      </div>
      <div class="w-full h-c-60 flex flex-j-c">
        <div class="h-full w-400 bgE8E6E7 overflow-y-auto border-box p-m" ref="leftBox">
          <div class="flex flex-j-c mb-6">
            <a-button type="text" :loading="loadingL" @click="nextPageL">
              {{ moreL ? '点击加载历史数据' : '没有更多了' }}
            </a-button>
          </div>
          <div
            class="bgfff round-6 flex p-10 mb-m"
            :class="current === item.id ? 'bgf3' : 'bgfff'"
            v-for="item in leftData"
            :key="item.id"
            :id="`${item.id}a`"
            @click="onLeftClick(item.id)"
          >
            <div class="w-128 h-128 mr-10 overflow-hidden">
              <a-image width="128" height="128" :src="item.picture[0]" fit="scale-down" />
            </div>
            <div class="flex-1 h-128 flex-col">
              <div class="w-full text-overflow-2 line-h-24">
                {{ item.title }}
              </div>
              <div class="flex flex-a-c flex-j-b text666 text-size-12 mt-10">
                <span>月销：{{ item.monthSales }}</span>
              </div>
              <div class="flex flex-a-c my-2">
                <span class="textd43030 text-size-14 font-bold mt-20"
                  ><span v-if="item.actualPrice">￥{{ item.actualPrice }}</span>
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="bgF4F4F4 w-700 h-full">
          <div class="bgfff box-border h-80 p-m flex pl-40 flex-a-c" v-if="itemMoment">
            <a-image :src="itemMoment.pic" :width="50" :height="50"></a-image>
            <span class="ml-10">{{ itemMoment.name }}</span>
          </div>
          <div class="h-c-80 w-700 overflow-y-auto" ref="rightBox">
            <div class="flex flex-j-c my-6">
              <a-button type="text" :loading="loadingR" @click="nextPageR('t')">
                {{ moreR ? '点击加载历史数据' : '没有更多了' }}
              </a-button>
            </div>
            <div class="w-full pr-6 pl-16 box-border mb-20" v-for="(item, index) in rightData" :key="index">
              <div class="my-20 flex flex-j-c">{{ item.createdAt }}</div>
              <div class="flex flex-j-e mb-20" v-for="(item2, index2) in item.rows" :key="index2" :id="`${item2.id}b`">
                <div class="flex-col flex-a-c">
                  <a-avatar :size="40">采</a-avatar>
                </div>
                <div class="ml-8 flex-1">
                  <div class="w-fit bgfff round-10" v-if="item2.msgType == 3">
                    <a-image width="120" :src="item2.content"></a-image>
                  </div>
                  <div class="w-full" v-if="item2.msgType == 47">
                    <a-image width="80%" :src="item2.content"></a-image>
                  </div>
                  <div
                    class="w-fit flex-center p-8 box-border round-10 space-pre-line bg75e5a2"
                    v-else-if="item2.msgType == 1"
                  >
                    {{ item2.content }}
                  </div>
                </div>
              </div>
            </div>
            <div class="flex flex-j-c my-6">
              <a-button type="text" :loading="loadingR" @click="nextPageR('b')">
                {{ moreR ? '点击加载下一页' : '没有更多了' }}
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script setup>
import { momentPreviewForGoods, momentPreviewForCopywriting } from '@/apis'

defineOptions({ name: 'materialPreview' })

const leftData = ref([])
const rightData = ref([])
const loadingL = ref(false)
const loadingR = ref(false)
const empty = ref(false)
const moreL = ref(true)
const moreR = ref(true)
const leftBox = ref()
const rightBox = ref()
const key = useRoute().fullPath
const itemMoment = ref()
const current = ref()
const firstLoadL = ref(true)
const leftParams = reactive({
  momentId: undefined,
  lastId: undefined,
  keyword: undefined
})
const rightParams = reactive({
  momentId: undefined,
  lastId: undefined,
  maxId: undefined
})
// 初始化表单值
onMounted(() => {
  if (sessionStorage.getItem(key) || history.state.item) {
    if (history.state.item) {
      sessionStorage.setItem(key, history.state.item)
    } else {
      history.state.item = sessionStorage.getItem(key)
    }
    itemMoment.value = JSON.parse(history.state.item)
  }
  leftParams.momentId = rightParams.momentId = itemMoment.value.momentId
  getLeftData()
  getRightData()
  leftBox.value?.addEventListener('scroll', scrollLFun)
  rightBox.value?.addEventListener('scroll', scrollRFun)
})

onUnmounted(() => {
  sessionStorage.removeItem(key)
})

const throttle = (fn, time) => {
  let timer = null
  return function () {
    if (!timer) {
      timer = setTimeout(function () {
        fn()
        timer = null
      }, time)
    }
  }
}

/*** 监听左侧滚动条*/
const scrollLFun = (e) => {
  if (e.target.scrollTop == 0) {
    current.value = undefined
    throttle(nextPageL(), 500)
  }
}
/*** 监听右侧滚动条*/
const scrollRFun = (e) => {
  if (e.target.scrollTop === 0) {
    throttle(nextPageR('t'), 500)
  } else if (Math.ceil(e.target.scrollTop + e.target.clientHeight) >= e.target.scrollHeight) {
    throttle(nextPageR('b'), 500)
  }
}
const getLeftData = async () => {
  try {
    loadingL.value = true
    const res = await momentPreviewForGoods(leftParams)
    const data = JSON.stringify(res.data) === '{}' ? [] : res.data
    empty.value = data.length == 0
    moreL.value = data.length > 0
    let elId = null
    if (leftData.value.length > 0) {
      elId = `${leftData.value[0].id}a`
    }
    leftData.value = data.reverse().concat(leftData.value)
    if (firstLoadL.value) {
      nextTick(() => {
        leftBox.value.scrollTop = leftBox.value.scrollHeight - leftBox.value.offsetHeight
      })
      firstLoadL.value = false
    } else {
      nextTick(() => {
        const el = document.getElementById(elId)
        leftBox.value.scrollTo({
          top: el.offsetTop - 140
        })
      })
    }
  } finally {
    loadingL.value = false
  }
}
const getRightData = async (str) => {
  try {
    loadingR.value = true
    const res = await momentPreviewForCopywriting(rightParams)
    const data = JSON.stringify(res.data) === '{}' ? [] : res.data
    empty.value = data.length == 0
    moreR.value = data.length > 0
    const lastId = rightData.value.length ? rightData.value[0].rows[rightData.value[0].rows.length - 1].id : null
    if (str === 't') {
      rightData.value = data.concat(rightData.value)
      if (lastId) {
        nextTick(() => {
          const elId = `${lastId}b`
          const el = document.getElementById(elId)
          rightBox.value.scrollTo({
            top: el.offsetTop - 220
          })
        })
      }
    } else {
      rightData.value = rightData.value.concat(data)
    }
  } finally {
    loadingR.value = false
  }
}

const nextPageL = () => {
  leftParams.lastId = leftData.value[0].id
  getLeftData()
}

const nextPageR = (str) => {
  rightParams.goodsId = current.value = undefined
  if (str === 't') {
    rightParams.maxId = undefined
    rightParams.lastId = rightData.value[0].rows[rightData.value[0].rows.length - 1].id
  } else if (str === 'b') {
    rightParams.lastId = undefined
    const length = rightData.value.length - 1
    rightParams.maxId = rightData.value[length].rows[rightData.value[length].rows.length - 1].id
  }
  getRightData(str)
}

const onLeftClick = async (id) => {
  if (current.value === id) return
  current.value = id
  const res = await momentPreviewForCopywriting({ momentId: rightParams.momentId, goodsId: current.value })
  const lastId = res.data[0].rows[res.data[0].rows.length - 1].id
  const res2 = await momentPreviewForCopywriting({ momentId: rightParams.momentId, lastId })
  rightData.value = res2.data.concat(res.data)
  nextTick(() => {
    const elId = `${lastId}b`
    const el = document.getElementById(elId)
    rightBox.value.scrollTo({
      top: el.offsetTop - 200
    })
  })
}

const onSearch = () => {
  leftData.value = []
  getLeftData()
}
</script>

<style lang="scss" scoped>
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  :deep(.arco-card-body) {
    height: 100%;
    padding: 0;
    overflow: hidden;
    box-sizing: border-box;
  }
}
.bg-theme {
  background: rgb(var(--primary-6));
}
.border-theme {
  box-sizing: border-box;
  border: 1px solid rgb(var(--primary-6));
  border-top: none;
}
.border-r-theme {
  box-sizing: border-box;
  border-right: 1px solid rgb(var(--primary-6));
}
.max-w-26 {
  max-width: calc(100% - 48px);
}
.space-pre-line {
  white-space: pre-line;
  word-break: break-all;
}
.bg75e5a2 {
  background: #75e5a2;
}
.bg-transparent {
  background: transparent;
}
.guise-mobile {
  :deep(.arco-btn-outline) {
    zoom: 0.6;
  }
}
.text50 {
  color: #505050;
}
.w-400 {
  width: 400px;
}
.bgE8E6E7 {
  background: #e8e6e7;
}
.w-128 {
  width: 128px;
}
.h-128 {
  height: 128px;
}
.textd43030 {
  color: #d43030;
}
.h-60 {
  height: 50px;
}
.h-c-60 {
  height: calc(100% - 60px);
}
.border-box {
  box-sizing: border-box;
}
.bgF4F4F4 {
  background: #f4f4f4;
}
.w-700 {
  width: 800px;
}
.h-80 {
  height: 80px;
}
.h-c-80 {
  height: calc(100% - 80px);
}
</style>
